package service

import (
	"context"
	"errors"
	"pmservice/db"
	"pmservice/graph/model"
)

// AdminNew is the resolver for the AdminNew field.
func (s *Service) AdminNew(ctx context.Context, input model.AdminNew) (*model.Admin, error) {
	hos := db.HospitalGet(s.Orm.DB, input.Hosuid)
	if hos == nil {
		return nil, errors.New("hos not found")
	}

	if db.AdminExist(s.Orm.DB, input.Hosuid, "", input.Account) {
		return nil, errors.New("账号已被使用")
	}

	d, err := db.AdminNew(s.Orm.DB, &input)
	if err != nil {
		return nil, errors.New("admin create failed")
	}

	return s.AdminGet(ctx, d.UID, "")
}

// AdminSave is the resolver for the AdminSave field.
func (s *Service) AdminSave(ctx context.Context, uid string, input model.AdminEdit) (bool, error) {
	admin := db.AdminGet(s.Orm.DB, uid)
	if admin == nil {
		return false, errors.New("admin not found")
	}

	if input.Account != nil && db.AdminExist(s.Orm.DB, admin.Hospital, uid, *input.Account) {
		return false, errors.New("account been used")
	}

	return db.AdminSave(s.Orm.DB, admin.Hospital, uid, &input), nil
}

// AdminDelete is the resolver for the AdminDelete field.
func (s *Service) AdminDelete(ctx context.Context, uid string) (bool, error) {
	return db.AdminDel(s.Orm.DB, uid), nil
}

// AdminResetPassword is the resolver for the AdminResetPassword field.
func (s *Service) AdminResetPassword(ctx context.Context, uid string, oldpass string) (*model.AdminResetPassResult, error) {
	newpass := "123456"
	if db.AdminUpdatePassword(s.Orm.DB, uid, oldpass, newpass) {
		return &model.AdminResetPassResult{
			Ok:      true,
			Newpass: &newpass,
		}, nil
	}

	return &model.AdminResetPassResult{
		Ok: false,
	}, nil
}

func (s *Service) AdminGetCompositeData(ctx context.Context, d *db.Admin, prefix string) (*model.Admin, error) {
	ret := d.ToGQL()
	if HasField(ctx, PrefixJoin(prefix, "hospital")) {
		ret.Hospital, _ = s.HospitalGet(ctx, d.Hospital, PrefixJoin(prefix, "hospital"))
	}

	return ret, nil
}

// AdminGet is the resolver for the AdminGet field.
func (s *Service) AdminGet(ctx context.Context, uid string, prefix string) (*model.Admin, error) {
	d := db.AdminGet(s.Orm.DB, uid)
	if d == nil {
		return nil, errors.New("admin not found")
	}

	return s.AdminGetCompositeData(ctx, d, prefix)
}

// AdminLogin is the resolver for the AdminLogin field.
func (s *Service) AdminLogin(ctx context.Context, account string, password string, prefix string) (*model.Admin, error) {
	d := db.AdminLogin(s.Orm.DB, account, password)
	if d == nil {
		return nil, errors.New("admin login failed")
	}

	return s.AdminGetCompositeData(ctx, d, prefix)
}
